// cloudfunctions/managenotifications/index.js
const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();

// --- *** 新增：管理员 OPENID *** ---
const ADMIN_OPENID = '41b03074e1bb154e164f0a56873bf6d0';

/**
 * 入口函数
 * @param {object} event - 包含 action (操作类型), notificationId (通知ID), data (操作数据)
 */
exports.main = async (event, context) => {
  const { action, notificationId, data } = event;

  // --- *** 新增：权限校验 *** ---
  const wxContext = cloud.getWXContext();
  const openid = wxContext.OPENID;

  if (openid !== ADMIN_OPENID) {
    return {
      success: false,
      message: '无权操作'
    };
  }
  // --- *** 权限校验结束 *** ---

  try {
    switch (action) {
      // 获取通知列表
      case 'getList':
        const res = await db.collection('notifications').orderBy('time', 'desc').get();
        return {
            success: true,
            data: res.data
        };
      
      // 发布新通知
      case 'add':
        if (!data || !data.title || !data.content) {
          return { success: false, message: '标题和内容不能为空' };
        }
        return await db.collection('notifications').add({
          data: {
            title: data.title,
            content: data.content,
            time: new Date(),
            type: data.type || 'system'
          }
        });

      // 删除通知
      case 'delete':
        if (!notificationId) {
          return { success: false, message: '缺少 notificationId' };
        }
        return await db.collection('notifications').doc(notificationId).remove();

      default:
        return {
          success: false,
          message: '未知的操作类型'
        }
    }
  } catch (e) {
    console.error('操作通知失败', e);
    return {
      success: false,
      error: e
    }
  }
};